package me.pearjelly.pmc.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;

import me.pearjelly.pmc.dao.DocDAO;
import me.pearjelly.pmc.service.InitialService;
import me.pearjelly.pmc.util.FileUtils;
import me.pearjelly.pmc.util.Logger;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class InitialServiceImpl implements InitialService {

	@Override
	public void index() {
		IndexWriter indexWriter = this.prepareWriter();
		if(indexWriter != null){
			int total = docDAO.selectCouldIndexCount();
			int count = total%maxRows == 0?total/maxRows : total/maxRows + 1; 
			int i=0;
			
			for(;i<count;i++){
				List<Document> list = docDAO.selectCouldIndex(i*maxRows, maxRows);
				for (Document document : list) {
					try {
						indexWriter.addDocument(document);
					} catch (IOException e) {
						log.error("Index document:%s IOException:%s", document, e.getMessage());
					}
					log.debug("Index document:%s", document);
				}
			}
			try {
				indexWriter.optimize();
				indexWriter.close();
			} catch (IOException e) {
				log.error("Close IndexWriter dir:%s IOException:%s", indexDir, e.getMessage());
			}
		}

	}
	
	/**
	 * 预锟斤拷锟斤拷锟斤拷锟斤拷目录锟斤拷
	 * 锟斤拷锟斤拷锟斤拷锟斤拷史锟斤拷荩锟斤拷锟缴撅拷锟�
	 * 锟斤拷锟侥柯硷拷锟斤拷锟斤拷冢锟斤拷虼唇锟斤拷锟�
	 * @return
	 */
	public IndexWriter prepareWriter(){
		File dir = new File(this.indexDir);
		if(dir.exists()){
			FileUtils.deleteOnRecursion(dir);
		}
		try {
			Directory directory = FSDirectory.open(dir);
			IndexWriter indexWriter = new IndexWriter(directory, this.analyzer, MaxFieldLength.LIMITED);
			return indexWriter;
		} catch (IOException e) {
			log.error("Prepare IndexWriter dir:%s IOException:%s", indexDir, e.getMessage());
		}
		return null;
	}
	
	private static final Logger log = new Logger();
	private DocDAO docDAO;
	private String indexDir = "/opt/pms/index/data";
	private Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_30);
	private int maxRows = 2000;

	public void setDocDAO(DocDAO docDAO) {
		this.docDAO = docDAO;
	}

	public void setIndexDir(String indexDir) {
		this.indexDir = indexDir;
	}

	public void setAnalyzer(Analyzer analyzer) {
		this.analyzer = analyzer;
	}

	public void setMaxRows(int maxRows) {
		this.maxRows = maxRows;
	}	
	
}
